package cn.zhf.shop.utils;

import cn.zhf.shop.utils.PayUtil;
import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author ClayeLink
 * @date 2022/2/27 11:29
 */
@Component
public class Schedule {

    private static String AccessToken;

    public void setAccessToken(String accessToken) {
        AccessToken = accessToken;
    }

    public static String getAccessToken() {
        return AccessToken;
    }

    /**
     * 获取银联商务AccessToken并转存
     * 可以使用redis进行存储维护十个AccessToken。
     * @return
     */
    @Scheduled(fixedRate = 50 * 60 * 1000)
    public void updateAccessToken(){
        String timestamp = PayUtil.getTimestamp();
        String nonce = PayUtil.getNonce();
        JSONObject content = new JSONObject();
        content.put("appId", PayUtil.APPID);
        content.put("timestamp", timestamp);
        content.put("nonce", nonce);
        content.put("signMethod", "SHA256");
        content.put("signature", PayUtil.sha256Hex(PayUtil.APPID+timestamp+nonce+PayUtil.APPKEY));
        JSONObject resp = PayUtil.doPost("https://api-mop.chinaums.com/v1/token/access",content,null);
        if (Integer.parseInt((String) resp.get("errCode")) == 0000){
            setAccessToken((String) resp.get("accessToken"));
        }else{
            updateAccessToken();
        }
    }
}
